package com.cjbdi.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cjbdi.entity.GongGao;
import com.cjbdi.entity.UserGonggao;
import com.cjbdi.entity.UserInfo;
import com.cjbdi.pagination.PageInfo;
import com.cjbdi.service.GonggaoService;
import com.cjbdi.service.UserGonggaoService;
import com.cjbdi.service.UserService;
import com.cjbdi.util.NumUtil;
import com.cjbdi.util.PropertiesUtil;
import com.cjbdi.util.StringEditor;
import com.cjbdi.vo.Result;
import com.cjbdi.vo.UserGonggaoVO;
import com.cjbdi.websocket.WebSocketServer;

@Controller
@RequestMapping("gonggao")
public class GonggaoController {
	@Autowired
    private UserService userService;
	
	@Autowired
    private GonggaoService gonggaoService;
	
	@Autowired
    private UserGonggaoService userGonggaoService;
    
    @RequestMapping(value = "/save", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Result save(GongGao gonggao) {
    	List<GongGao> list = gonggaoService.findByTitle(gonggao.getTitle());
    	if(list.size()>0) {
    		return new Result(601,"公告已经存在",null);
    	}else {
    		gonggao.setTag("未发送");
    		gonggao.setSender("admin");
    		gonggao.setUpdateTime(NumUtil.GetNowDate("yyyy-MM-dd HH:mm:ss"));
    		gonggao.setSentTime("");
    		gonggao.setFybm(gonggao.getFybm().startsWith(";")?gonggao.getFybm().substring(1):gonggao.getFybm());
    		gonggao.setFymc(gonggao.getFymc().startsWith(";")?gonggao.getFymc().substring(1):gonggao.getFymc());
    		gonggaoService.save(gonggao);
        	return new Result(200,"新增公告成功",null);

    	}
    	
    }

    @RequestMapping(value = "/edit", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Result edit(int id) {
    	List<GongGao> list = gonggaoService.findById(id);
    	if(list.size()>0) {
    		return new Result(200,"获取公告信息成功",list.get(0));
    	}else {
        	return new Result(602,"获取公告信息失败",null);

    	}
    	
    }
    @RequestMapping(value = "/update", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
	public Result update(GongGao gonggao) {
    	List<GongGao> list = gonggaoService.findById(gonggao.getId());
    	if(list.size()>0) {
    		GongGao gonggaoOld = list.get(0);
    		gonggaoOld.setContent(gonggao.getContent());
    		gonggaoOld.setUpdateTime(NumUtil.GetNowDate("yyyy-MM-dd HH:mm:ss"));
    		gonggaoOld.setFybm(gonggao.getFybm().startsWith(";")?gonggao.getFybm().substring(1):gonggao.getFybm());
    		gonggaoOld.setFymc(gonggao.getFymc().startsWith(";")?gonggao.getFymc().substring(1):gonggao.getFymc());
    		gonggaoOld.setTag("未发送");
    		gonggaoService.save(gonggaoOld);
    		return new Result(200, "修改公告成功", null);
    	}else {
    		return new Result(603, "修改公告失败", null);
    	}

	}
    @RequestMapping(value = "/page", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> page(@RequestParam(value = "limit", required = false, defaultValue = "10") String limit,
			@RequestParam(value = "offset", required = false, defaultValue = "0") String offset,GongGao gonggao) {
    	Sort sort = new Sort(Direction.DESC,"id");
    	Pageable pageable = PageRequest.of(Integer.valueOf(offset)/Integer.valueOf(limit), Integer.valueOf(limit), sort);
		PageInfo<GongGao> pageInfo = gonggaoService.getPageByParam(gonggao.getTitle()==null?"":gonggao.getTitle(), gonggao.getFymc()==null?"":gonggao.getFymc(),gonggao.getTag()==null?"":gonggao.getTag(), pageable);
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("count", pageInfo.getRecords());
		result.put("queryData", pageInfo.getRows());
		return result;
    }
    @RequestMapping("/delete")
    @ResponseBody
    public Result delete(int id){
    	boolean a = gonggaoService.delete(id);
    	boolean b = userGonggaoService.delete(id);
    	if(a&b) {
    		return new Result(200,"删除公告成功",null);
		}else {
			return new Result(604,"删除公告失败",null);
		}
    }
    
    @RequestMapping(value ="/saveAndPublish", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Result saveAndPublish(GongGao gonggao){
    	List<GongGao> list = gonggaoService.findByTitle(gonggao.getTitle());
    	if(list.size()>0) {
    		return new Result(605,"公告名称已经存在，请重新编辑后再发送",null);
    	}else {
    		gonggao.setTag("已发送");
    		gonggao.setSender("admin");
    		gonggao.setUpdateTime(NumUtil.GetNowDate("yyyy-MM-dd HH:mm:ss"));
    		gonggao.setSentTime(NumUtil.GetNowDate("yyyy-MM-dd HH:mm:ss"));
    		gonggao.setFybm(gonggao.getFybm().startsWith(";")?gonggao.getFybm().substring(1):gonggao.getFybm());
    		gonggao.setFymc(gonggao.getFymc().startsWith(";")?gonggao.getFymc().substring(1):gonggao.getFymc());
    		gonggaoService.save(gonggao);
    		insertIntoUserGong(gonggao);//插入用户公告关联表
    		WebSocketServer webSocketServer = new WebSocketServer();
        	try {
    			webSocketServer.sendtoUser(gonggao.getContent(),gonggao.getFybm());
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
        	return new Result(200,"发送公告成功",null);
    	}
    }
    
    @RequestMapping(value ="/publish", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Result publish(int id){
    	List<GongGao> list = gonggaoService.findById(id);
    	if(list.size()>0) {
    		GongGao gonggao = list.get(0);
    		gonggao.setTag("已发送");
    		gonggao.setSentTime(NumUtil.GetNowDate("yyyy-MM-dd HH:mm:ss"));
    		gonggaoService.save(gonggao);//插入公告表
    		insertIntoUserGong(gonggao);//插入用户公告关联表
    		WebSocketServer webSocketServer = new WebSocketServer();
        	try {
    			webSocketServer.sendtoUser(gonggao.getContent(),gonggao.getFybm());
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
        	return new Result(200,"发送公告成功",null);
    	}else {
    		return new Result(607, "发送公告失败", null);
    	}
    }
    
    public void insertIntoUserGong(GongGao gonggao) {
    	String[] fybms = gonggao.getFybm().split(";");
    	List<String> fybm = Arrays.asList(fybms); 
    	List<UserInfo> list = userService.findByFybm(fybm);
    	for(int i=0;i<list.size();i++) {
    		UserInfo user = list.get(i);
    		UserGonggao userGonggao = new UserGonggao();
    		userGonggao.setUserid(user.getId());
    		userGonggao.setUserip(user.getUserip());
    		userGonggao.setGonggaoid(gonggao.getId());
    		userGonggao.setStatus("未读");
    		userGonggaoService.save(userGonggao);
    	}
    }
    
    @RequestMapping(value ="/updateAndPublish", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Result updateAndPublish(GongGao gonggao){
    	List<GongGao> list = gonggaoService.findById(gonggao.getId());
    	if(list.size()>0) {
    		GongGao gonggaoOld = list.get(0);
    		gonggaoOld.setContent(gonggao.getContent());
    		gonggaoOld.setUpdateTime(NumUtil.GetNowDate("yyyy-MM-dd HH:mm:ss"));
    		gonggaoOld.setSentTime(NumUtil.GetNowDate("yyyy-MM-dd HH:mm:ss"));
    		gonggaoOld.setFybm(gonggao.getFybm().startsWith(";")?gonggao.getFybm().substring(1):gonggao.getFybm());
    		gonggaoOld.setFymc(gonggao.getFymc().startsWith(";")?gonggao.getFymc().substring(1):gonggao.getFymc());
    		gonggaoOld.setTag("已发送");
    		gonggaoService.save(gonggaoOld);
    		insertIntoUserGong(gonggaoOld);//插入用户公告关联表
    		WebSocketServer webSocketServer = new WebSocketServer();
        	try {
    			webSocketServer.sendtoUser(gonggao.getContent(),gonggao.getFybm());
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
        	return new Result(200,"发送公告成功",null);
    	}else {
    		return new Result(606, "发送公告失败", null);
    	}
    }
    
    /*@RequestMapping(value ="/getLastGonggao", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Result getLastGonggao(String fybm){
    	List<GongGao> list = gonggaoService.getLastGonggao(fybm);
    	if(list.size()>0) {
    		return new Result(200,"获取公告信息成功",list.get(0));
    	}else {
    		return new Result(607,"暂无公告",null);
    	}
    }*/
    
    @CrossOrigin
    @RequestMapping(value ="/getGonggaobyIp", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Result getGonggaobyIp(String ip){
		List list = userGonggaoService.getGonggaobyIp(ip);
		List<UserGonggaoVO> result =  new ArrayList();
    	if(list.size()>0) {
    		for(int i=0;i<list.size();i++) {
    			Object[] o = (Object[])list.get(i);
    			UserGonggaoVO usergonggao = new UserGonggaoVO();
    			usergonggao.setUserip(o[0].toString());
    			usergonggao.setContent(o[1].toString());
    			usergonggao.setStatus(o[2].toString());
    			usergonggao.setTitle(o[3].toString());
    			usergonggao.setGonggaoid((Integer)o[4]);
    			result.add(usergonggao);
    		}
    		return new Result(200,"获取公告信息成功",result);
    	}else {
    		return new Result(607,"暂无公告",null);
    	}
    }
    
    @CrossOrigin
    @RequestMapping(value ="/updateGonggaoStatus", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Result updateGonggaoStatus(String ip,int gonggaoid){
    	List<UserGonggao> list = userGonggaoService.getGonggaobyIpAndid(ip,gonggaoid);
    	if(list.size()>0) {
    		UserGonggao userGonggao = list.get(0);
    		userGonggao.setStatus("已读");
    		userGonggaoService.save(userGonggao);
    		return new Result(200,"更新公告信息成功",list);
    	}else {
    		return new Result(608,"获取公告信息失败",null);
    	}
    }
    
    
    @RequestMapping(value = "/info", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Result info(int gonggaoid) {
    	List list = userGonggaoService.getGonggaobyId(gonggaoid);
    	String yidu ="";
    	String weidu ="";
    	if(list.size()>0) {
    		for(int i=0;i<list.size();i++) {
    			Object[] o = (Object[])list.get(i);
    			if(o[1].toString().equals("已读"))
    			{
    				yidu = yidu +"\n" +o[0]+"("+o[4]+")";
    			}else if(o[1].toString().equals("未读"))
    			{
    				weidu = weidu +"\n" +o[0]+"("+o[4]+")";
    			}
    		}
    		Map map = new HashMap();
    		map.put("yidu", yidu.replaceFirst("\n", ""));
    		map.put("weidu", weidu.replaceFirst("\n", ""));
    		return new Result(200,"获取公告发送信息成功",map);
    	}else {
        	return new Result(609,"获取公告发送信息失败",null);

    	}
    	
    }
}
